8935. Odds in the interval

 

Print all odd integers from the interval [a, b] in ascending order.

 

Input. Two integers a and b (ab).

 

Output. Print all odd integers from the interval [a, b] in ascending order on a single line.

 

Sample input

Sample output

2 7

3 5 7

 

 

SOLUTION

loop

 

Algorithm analysis

Use a for loop. Iterate through all numbers from a to b in ascending order and print only the odd ones.

 

Algorithm implementation

Read the input data.

 

scanf("%d %d", &a, &b);

 

Iterate through all numbers from a to b in ascending order and print only the odd ones.

 

for (i = a; i <= b; i++)

  if (i % 2 == 1) printf("%d ", i);

 

Java implementation

 

import java.util.*;

 

class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int a = con.nextInt();

    int b = con.nextInt();

    for(int i = a; i <= b; i++)

      if (i % 2 == 1) System.out.print(i + " ");

    con.close();

  }

}

 

Python implementation

Read the input data.

 

a, b = map(int, input().split())

 

Iterate through all numbers from a to b in ascending order and print only the odd ones.

 

for i in range(a, b + 1):

  if i % 2 == 1: print(i, end=" ")

 

Python implementation – list

Read the input data.

 

a, b = map(int, input().split())

 

Create a list containing all the odd numbers from the interval [a, b].

 

res = [x for x in range(a, b + 1) if x % 2 != 0]

 

Print the answer.

 

print(*res)